package com.xc.utils;

import com.ag.exception.SysTipsException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@Slf4j
public class HolidayUtil {

    public static final String key = PropertiesUtil.getProperty("tianapi.key");

    /**
     * 请求接口获取节假日信息
     *
     * @param httpArg 日期数据
     * @return 返回结果
     */
    public static boolean request(String httpArg) {
        String httpUrl = "https://apis.tianapi.com/jiejiari/index?key=" + key + "&date=" + httpArg;
        BufferedReader reader;
        String result;
        StringBuffer sbf = new StringBuffer();
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
            }
            reader.close();
            result = sbf.toString();
            JSONObject jsonObject = JSON.parseObject(result);
            if (200 == (jsonObject.getInteger("code"))) {
                JSONObject resultObj = jsonObject.getJSONObject("result");
                JSONArray list = resultObj.getJSONArray("list");
                JSONObject holidayObj = (JSONObject) list.get(0);
                Integer dayCode = holidayObj.getInteger("daycode");
                return dayCode == 1 || dayCode == 2;
            } else {
                throw new SysTipsException("查询节假日接口出错");
            }
        } catch (Exception e) {
            log.error("查询节假日接口出错");
            throw new SysTipsException("查询节假日接口出错");
        }
    }

    /*public static void main(String[] args) {
        // 处理节假日
        String httpArg = "20190720";
		*//*SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
		httpArg = f.format(new Date());*//*
        String jsonResult = HolidayUtil.request(httpArg);
        // 0 上班  1周末 2节假日
        if ("0".equals(jsonResult)) {
            //return resultObject.getFailResult("上班");
            System.out.println("0上班");
        }
        if ("1".equals(jsonResult)) {
            //return resultObject.getFailResult("1周末");
            System.out.println("1周末");
        }
        if ("2".equals(jsonResult)) {
            //return resultObject.getFailResult("");
            System.out.println("2节假日");
        }
    }*/

}
